package com.opennews.openplatform.familyexpenseapi.controller

import com.opennews.openplatform.myspringbootcore.common.constant.ERROR_USER_ACCOUNT_NOT_AUTHORIZED
import com.opennews.openplatform.myspringbootcore.common.constant.HTTP_HEADER_AUTHORIZATION
import com.opennews.openplatform.myspringbootcore.common.constant.SERVER_UNAUTHORIZED
import com.opennews.openplatform.myspringbootcore.security.AuthRequestValidator
import com.opennews.openplatform.myspringbootmvccore.extension.sendErrorResponse
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.servlet.HandlerInterceptor

@Component
class AuthInterceptor(
    private val authRequestValidator: AuthRequestValidator,
) : HandlerInterceptor {
    override fun preHandle(
        request: HttpServletRequest,
        response: HttpServletResponse,
        handler: Any,
    ): Boolean {
        println(request.requestURI)

        val granted = authRequestValidator.checkAccessPermission(
            request.method,
            request.requestURI.trim(),
            request.contextPath.trim(),
            request.getHeader(HTTP_HEADER_AUTHORIZATION)?.trim(),
        )

        if (!granted) {
            response.sendErrorResponse(
                HttpStatus.UNAUTHORIZED.value(),
                SERVER_UNAUTHORIZED,
                ERROR_USER_ACCOUNT_NOT_AUTHORIZED,
                request.requestURI.trim(),
            )
        }

        return granted
    }
}